const models = require('./../db/mysqldb/index')
const { ErrorModel, SuccessModel, encrypt } = require('./../utils/index')
const logger = require('./../utils/logger')
const config = require('./../config/index')
const sysProjectList = require("./../libs/dfProjectList")
const sysPageList = require("./../libs/dfPageList")
const compList = require("./../libs/dfCompList")
const compLibList = require("./../libs/dfCompLibList")
const { generatePageUrl } = require("../utils/index")

class SystemController {
  static async init (req, res, next) {
    try {
      await models.sequelize.sync({})
      await res.json(new SuccessModel(`mysql table create success`))
    } catch (error) {
      await res.json(new ErrorModel(`错误信息：${error.message}`))
    }
  }
  static async addAdmin (req, res, next) {
    try {
      const password = await encrypt(config.admin_password, config.saltTime)
      const userRes = await models.sys_user.bulkCreate([{
        user_id: 1,
        username: 'admin',
        password,
        realname: 'admin',
        phone: '17034642112',
        avatar: "https://up.enterdesk.com/edpic/1a/e6/e9/1ae6e9ba84a1ba54566947a68f2fa35d.jpeg",
        sex: 1,
        status: 0,
      }, {
        user_id: 2,
        username: 'cherry',
        password,
        realname: '樱桃小丸子',
        phone: '17034642113',
        avatar: "https://up.enterdesk.com/edpic/a2/20/77/a22077cf0c937330544a02ea28c75fa3.jpg",
        sex: 1,
        status: 0,
      }, {
        user_id: 3,
        username: 'orange',
        password,
        realname: '少女阿九',
        phone: '17034642114',
        avatar: "https://up.enterdesk.com/edpic/1a/e6/e9/1ae6e9ba84a1ba54566947a68f2fa35d.jpeg",
        sex: 1,
        status: 0,
      }])
      logger.info(`SystemController`, `addAdmin`, userRes)
      const projectRes = await models.project.bulkCreate(sysProjectList)
      logger.info(`SystemController`, `addAdmin`, projectRes)
      await models.page.bulkCreate(sysPageList)
      const pageListRes = await models.page.findAll();
      pageListRes.map(async item => {
        let page_url = generatePageUrl(item.project_id, item.page_id)
        await models.page.update(
          {
            page_url,
          },
          {
            where: { page_id: item.page_id },
          }
        )
      })
      const compRes = await models.comp.bulkCreate(compList)
      logger.info(`SystemController`, `addAdmin`, compRes)
      const compLibRes = await models.comp_lib.bulkCreate(compLibList)
      logger.info(`SystemController`, `addAdmin`, compLibRes)
      await res.json(new SuccessModel(`admin data create success`))
    } catch (error) {
      logger.info(`SystemController`, `addAdmin`, error.message)
      await res.json(new ErrorModel(`错误信息：${error.message}`))
    }
  }
}

module.exports = {
  SystemController
}
